#!/usr/bin/env bash

# set -e: exit asap if a command exits with a non-zero status
# set -x: print each command right before it is executed
set -xe

docker --version
docker-compose --version

if [[ ${TRAVIS_PULL_REQUEST_SLUG} != "" && \
      ${TRAVIS_PULL_REQUEST_SLUG} != ${TRAVIS_REPO_SLUG} && \
      ${TRAVIS_PULL_REQUEST} != "false" ]]; then
  echo "WARN: External PRs are untrusted by default therefore we need can't reuse and push the image"
  exit 0
fi

pip install --upgrade -r test/requirements.txt

# We always need to login to docker to avoid: toomanyrequests
[ "${DOCKER_USERNAME}" == "" ] && die "Need env var DOCKER_USERNAME to pull/push to docker"
[ "${DOCKER_PASSWORD}" == "" ] && die "Need env var DOCKER_PASSWORD to pull/push to docker"

docker login -u="${DOCKER_USERNAME}" -p="${DOCKER_PASSWORD}"
echo "Logged in to docker with user '${DOCKER_USERNAME}'"

./host-scripts/gen-scm-source.sh
docker build -t selenium .
docker tag selenium:latest elgalu/selenium:latest
docker images selenium

if [ "${TRAVIS_BUILD_NUMBER}" != "" ]; then
  # Let's push this image to re-use it in TravisCI stages
  # in order to speed up the build
  docker tag selenium:latest elgalu/build_selenium:${TRAVIS_BUILD_NUMBER}
  docker push elgalu/build_selenium:${TRAVIS_BUILD_NUMBER}
fi
